package com.lykj.llw.box.ui.activity

import android.content.Intent
import android.content.res.Configuration
import android.os.Build
import android.os.Bundle
import android.text.Html
import android.util.Log
import android.view.View
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.CacheDiskUtils
import com.blankj.utilcode.util.GsonUtils
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions.withCrossFade
import com.gyf.immersionbar.BarHide
import com.gyf.immersionbar.ImmersionBar
import com.lykj.lib_base.app.BaseApplication
import com.lykj.lib_base.base.BaseActivity
import com.lykj.lib_base.bus.FlowBus
import com.lykj.lib_base.component.GlideApp
import com.lykj.lib_base.constants.BConstants
import com.lykj.lib_base.internal.extfun.clickWithTrigger
import com.lykj.lib_base.internal.utils.PackageUtils
import com.lykj.lib_base.internal.utils.ToastUtils
import com.lykj.lib_base.net.http.CustomResponseBodyObserver
import com.lykj.lib_base.net.http.RetrofitManager
import com.lykj.llw.box.R
import com.lykj.llw.box.adapter.HorFivePicAdapter
import com.lykj.llw.box.data.bean.response.GameDetailResponse
import com.lykj.llw.box.data.model.LocalDownloadRecordModel
import com.lykj.llw.box.databinding.ActGameDetailBinding
import com.lykj.llw.box.ui.diafrg.ShareDiaFrg
import com.lykj.llw.box.utils.DialogUtils
import com.lykj.llw.box.utils.DownloadManagerUtils
import com.shuyu.gsyvideoplayer.GSYVideoManager
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack
import com.shuyu.gsyvideoplayer.utils.GSYVideoType
import com.shuyu.gsyvideoplayer.utils.OrientationUtils
import com.shuyu.gsyvideoplayer.video.base.GSYVideoPlayer
import io.reactivex.disposables.Disposable
import okhttp3.ResponseBody
import org.json.JSONObject


/**
 * ================================================
 * 游戏详情页
 * ================================================
 *
 * @author gosha
 * @date 2023/10/19-14:16
 */
class GameDetailActivity : BaseActivity() {
    lateinit var binding: ActGameDetailBinding

    private val TAG = "GameDetail"
    private var mBean: GameDetailResponse.DataDTO? = null
    private val mPicAdapter = HorFivePicAdapter()
    private val mPicData = ArrayList<String>()

    private var downloadUrl = ""
    private var filePath: String = ""
    private var fileName: String = ""

    var url: String = ""
    var gid = 0

    private var mResponseStr = ""

    private var isPlay = false
    private var isPause = false

    private var orientationUtils: OrientationUtils? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActGameDetailBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initUI()
        initData()
        setListener()
    }

    override fun onResume() {
        getCurPlay()?.onVideoResume(false)
        super.onResume()
        isPause = false

        ImmersionBar.with(this)
            .transparentBar()
//            .statusBarDarkFont(true) //状态栏字体是深色，不写默认为亮色
//            .navigationBarDarkIcon(true)
            .hideBar(BarHide.FLAG_HIDE_NAVIGATION_BAR)
            .navigationBarEnable(false)
            .init()

        DownloadManagerUtils.getDownloadInfoFromLocal()
        //刷新状态游戏是否安装状态
        mBean?.let {
            dealWithDownloadBtnText(it)
        }
    }

    override fun onPause() {
        getCurPlay()?.onVideoPause()
        super.onPause()
        isPause = true
    }

    override fun onBackPressed() {
        // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
        // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
        orientationUtils?.backToProtVideo()

        if (GSYVideoManager.backFromWindowFull(this)) {
            return
        }
        super.onBackPressed()
    }

    private fun getCurPlay(): GSYVideoPlayer? {
        return if (binding.sPlayer.fullWindowPlayer != null) {
            binding.sPlayer.fullWindowPlayer
        } else binding.sPlayer
    }

    /**
     * orientationUtils 和 onConfigurationChanged 方法是用于触发屏幕旋转的
     */
    override
    fun onConfigurationChanged(p0: Configuration) {
        super.onConfigurationChanged(p0)
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            binding.sPlayer.onConfigurationChanged(
                this,
                p0,
                orientationUtils,
                true,
                true
            )
        }
    }

    override fun initUI() {
        binding.sPlayer.titleTextView.visibility = View.GONE
        binding.sPlayer.backButton.visibility = View.GONE

        initRecyclerView()

        //申请礼包后,刷新游戏详情
        FlowBus.with<String>("update_card").register(this) {
            obtainGameDetail()
        }

        FlowBus.withStick<LocalDownloadRecordModel>(BConstants.BUS_KEY.DOWNLOAD_REFRESH)
            .register(this) {
                if (it.gameId == gid) {
                    //刷新下载进度条
                    when (it.status) {
                        0 -> {
                            //刷新下载进度
                            binding.tvBtnDownload.text = "${it.progress}%"
                            binding.rcpbDown.setProgress(it.progress)
                        }

                        1 -> {
                            //下载完成
                            binding.rcpbDown.setProgress(100)
                            binding.tvBtnDownload.text = "立即安装"
                            val instanceName = "@${
                                Integer.toHexString(
                                    System.identityHashCode(
                                        it
                                    )
                                )
                            }"
                            Log.e(TAG, "${it.gameId}==${instanceName}::${it.progress}")
                        }

                        -1 -> {
                            //下载停止
                            binding.tvBtnDownload.text = "继续"
                        }
                    }
                }
            }
    }


    private fun initRecyclerView() {
        val linearLayoutManager = LinearLayoutManager(this)
        linearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
        binding.rcv5pic.layoutManager = linearLayoutManager
        binding.rcv5pic.setHasFixedSize(true)
        mPicAdapter.data = mPicData
        mPicAdapter.setOnItemClickListener { adapter, view, position ->
//            val intent = Intent(this@GameDetailActivity, ImageDisplayActivity::class.java)
//            intent.putExtra("pic", mPicData[position])
//            startActivity(intent)

            val intent = Intent(this@GameDetailActivity, MultiImageDisplayActivity::class.java)
            intent.putStringArrayListExtra("pics", mPicData)
            intent.putExtra("index", position)
            startActivity(intent)
        }
        binding.rcv5pic.adapter = mPicAdapter
    }

    //获取游戏详情
    private fun obtainGameDetail() {
        DialogUtils.show(supportFragmentManager)
        clearBodyParam()
        initBodyParam()
        bodyParams["id"] = gid
        RetrofitManager.instance.obtainGameDetail(object :
            CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@GameDetailActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                DialogUtils.dismiss()
                val bean = GsonUtils.fromJson(responseBody, GameDetailResponse::class.java)
                mResponseStr = responseBody

                mBean = bean.data
                setUIAttr(bean.data)

                CacheDiskUtils.getInstance("game_detail").put("$gid", responseBody)
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@GameDetailActivity, msg)
                }
            }

        }, bodyParams)
    }

    //收藏/取消游戏
    private fun collectGame() {
        clearBodyParam()
        initBodyParam()
        bodyParams["gameId"] = gid
        bodyParams["type"] = 1
        RetrofitManager.instance.collectGame(object : CustomResponseBodyObserver<ResponseBody>() {
            override fun onSubscribe(d: Disposable) {
                addDisposables(this@GameDetailActivity, d)
            }

            override fun specificHandle(responseBody: String) {
                ToastUtils.showShort(
                    this@GameDetailActivity,
                    if (mBean!!.isCollect) "取消收藏成功" else "收藏成功"
                )

                obtainGameDetail()
            }

            override fun handleException(ret: String, msg: String?) {
                msg?.let {
                    ToastUtils.showShort(this@GameDetailActivity, it)
                }
            }

        }, bodyParams)
    }

    //获取下载地址
    private fun obtainDownloadUrl() {
        RetrofitManager.instance.obtainDownloadUrl("http://fenbao.66wsy.com/sdk87/nologin/apk/download?param=$gid-${BaseApplication.instance?.getUserInfo()?.channelId}",
            object : CustomResponseBodyObserver<ResponseBody>() {
                override fun onSubscribe(d: Disposable) {
                    addDisposables(this, d)
                }

                override fun specificHandle(responseBody: String) {
                    val jsonObject = JSONObject(responseBody)
                    url = jsonObject.getString("data")

                    if (PackageUtils.canRequestPackageInstalls(this@GameDetailActivity)) {
                        downloadAndInstall()
                    } else {
                        PackageUtils.showSettingPackageInstall(this@GameDetailActivity)
                    }
                }

                override fun handleException(ret: String, msg: String?) {
                    //FIXME:后期需求
//                    binding.tvBtnDownload.text = "等待下载"
                    msg?.let { ToastUtils.showShort(this@GameDetailActivity, it) }
                }
            })
    }

    //设置属性
    private fun setUIAttr(data: GameDetailResponse.DataDTO) {
        binding.tvGameName.text = "${data.gamename}"
        binding.tvDetailLabel.text = "${data.collection} ${data.gametype}"

        GlideApp.with(this)
            .load(data.bgPic)
            .transition(withCrossFade())
            .into(binding.ivDetailCover)

        GlideApp.with(this)
            .load(data.icon)
            .transition(withCrossFade())
            .into(binding.ivIcon)

        downloadUrl = data.downloadUrl

        //是否0.1折
        binding.ivDiscount.visibility = if (data.payRatio == 0.01f) View.VISIBLE else View.GONE

        if (data.type == 2) {//会员游戏
            binding.ivDiscount.visibility = View.VISIBLE
            binding.ivDiscount.setImageResource(R.mipmap.ic_vip_gift_bag)
        }

        if (data.videoUrl.isNullOrBlank()) {
            binding.sPlayer.visibility = View.GONE
            binding.ivDetailCover.visibility = View.VISIBLE
        } else {
            binding.sPlayer.visibility = View.VISIBLE
            binding.ivDetailCover.visibility = View.GONE

            //设置视频播放器
            orientationUtils = OrientationUtils(this, binding.sPlayer)
            orientationUtils?.isEnable = false

            //增加封面
            val imageView = ImageView(this)
            imageView.scaleType = ImageView.ScaleType.CENTER_CROP
            GlideApp.with(this)
                .load(data.bgPic)
                .transition(withCrossFade())
                .into(imageView)

            val header: MutableMap<String, String> = HashMap()
            header["allowCrossProtocolRedirects"] = "true"
            val gsyVideoOption = GSYVideoOptionBuilder()
            gsyVideoOption
                .setThumbImageView(imageView)
                .setIsTouchWiget(true)
                .setMapHeadData(header)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setAutoFullWithSize(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setUrl(data.videoUrl)
                .setCacheWithPlay(true)
//            .setVideoTitle("测试视频")
                .setVideoAllCallBack(object : GSYSampleCallBack() {
                    override fun onPrepared(url: String?, vararg objects: Any?) {
                        super.onPrepared(url, *objects)

                        //开始播放了才能旋转和全屏
                        orientationUtils!!.isEnable = binding.sPlayer.isRotateWithSystem()
                        isPlay = true

                    }

                    override fun onQuitFullscreen(url: String?, vararg objects: Any?) {
                        super.onQuitFullscreen(url, *objects)
                        // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
                        // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
                        if (orientationUtils != null) {
                            orientationUtils!!.backToProtVideo()
                        }
                    }
                })
                .setLockClickListener { view, lock ->
                    if (orientationUtils != null) {
                        //配合下方的onConfigurationChanged
                        orientationUtils!!.isEnable = !lock
                    }
                }
                .build(binding.sPlayer)

            GSYVideoType.setShowType(GSYVideoType.SCREEN_MATCH_FULL)

            binding.sPlayer.fullscreenButton.setOnClickListener {
                //直接横屏
                // ------- ！！！如果不需要旋转屏幕，可以不调用！！！-------
                // 不需要屏幕旋转，还需要设置 setNeedOrientationUtils(false)
                orientationUtils!!.resolveByClick()

                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                binding.sPlayer.startWindowFullscreen(this@GameDetailActivity, false, true)
            }
        }

        if (data.subject.isNullOrBlank()) {
            binding.tvSummeryDesc.visibility = View.GONE
            binding.tvSummeryDesc2.visibility = View.GONE
            binding.tvContent.visibility = View.GONE
        } else {
            val subject =
                data.subject.replace("&nbsp", "").replace("&lt;", "<").replace("&gt;", ">")
                    .replace("&amp;", "&").replace("&cent;", "¢").replace("&pound;", "£")
                    .replace("&yen;", "¥").replace("&euro;", "€").replace("&sect;", "§")
                    .replace("&copy;", "©").replace("&reg;", "®").replace("&trade;", "™")

            binding.tvSummeryDesc.visibility = View.VISIBLE
            binding.tvSummeryDesc2.visibility = View.VISIBLE
            binding.tvContent.visibility = View.VISIBLE
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                binding.tvContent.text = Html.fromHtml(subject, Html.FROM_HTML_MODE_LEGACY)
            } else {
                binding.tvContent.text = Html.fromHtml(subject)
            }
        }

        if (data.fuli.isNullOrBlank()) {
            binding.tvWelfareDesc.visibility = View.GONE
            binding.tvWelfare.visibility = View.GONE
        } else {
            val fuli =
                data.fuli.replace("&nbsp", "").replace("&lt;", "<").replace("&gt;", ">")
                    .replace("&amp;", "&").replace("&cent;", "¢").replace("&pound;", "£")
                    .replace("&yen;", "¥").replace("&euro;", "€").replace("&sect;", "§")
                    .replace("&copy;", "©").replace("&reg;", "®").replace("&trade;", "™")

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                binding.tvWelfare.text = Html.fromHtml(fuli, Html.FROM_HTML_MODE_LEGACY)
            } else {
                binding.tvWelfare.text = Html.fromHtml(fuli)
            }

            binding.tvWelfareDesc.visibility = View.VISIBLE
            binding.tvWelfare.visibility = View.VISIBLE
        }

        //收藏,点赞
        if (data.isCollect) {
            binding.ivCollect.setImageResource(R.mipmap.ic_detail_collect)
        } else {
            binding.ivCollect.setImageResource(R.mipmap.ic_detail_uncollect)
        }

        //设置游戏5图
        mPicData.clear()
        if (!data.pic1.isNullOrEmpty()) {
            mPicData.add(data.pic1)
        }
        if (!data.pic2.isNullOrEmpty()) {
            mPicData.add(data.pic2)
        }
        if (!data.pic3.isNullOrEmpty()) {
            mPicData.add(data.pic3)
        }
        if (!data.pic4.isNullOrEmpty()) {
            mPicData.add(data.pic4)
        }
        if (!data.pic5.isNullOrEmpty()) {
            mPicData.add(data.pic5)
        }
        mPicAdapter.notifyDataSetChanged()
        binding.tvBtnDownload.text = "立即下载/打开"
        dealWithDownloadBtnText(data)
    }

    //处理下载按钮显示文本逻辑
    private fun dealWithDownloadBtnText(data: GameDetailResponse.DataDTO) {
        //进度条重置
        binding.rcpbDown.setProgress(100)
        if (PackageUtils.checkApk(this, data.apkname)) {
            binding.tvBtnDownload.text = "打开"
        } else {
            if (DownloadManagerUtils.judgementDownloadIsExit(gid)) {
                //FIXME:有下载记录,未下载完成
                if (DownloadManagerUtils.getDownloadRecordInfo(gid)?.status == 1) {
                    binding.tvBtnDownload.text = "立即安装"
                } else if (DownloadManagerUtils.getDownloadRecordInfo(gid)?.status == 2) {
                    binding.tvBtnDownload.text = "下载中"
                } else {
                    binding.tvBtnDownload.text = "下载（${mBean?.gamesize}）"
                }
            } else {
                binding.tvBtnDownload.text = "下载（${mBean?.gamesize}）"
            }

        }
    }

    override fun initData() {
        DownloadManagerUtils.getDownloadInfoFromLocal()

        gid = intent.getIntExtra("gid", 0)
        filePath = getExternalFilesDir("apk")?.path ?: ""
        fileName = "$gid.apk"

        //TODO:优先获取本地缓存,不存在缓存使用请求,页面通过下拉刷新
        val cacheStr = CacheDiskUtils.getInstance("game_detail").getString("$gid")
        if (cacheStr.isNullOrBlank()) {
            obtainGameDetail()
        } else {
            val bean = GsonUtils.fromJson(
                cacheStr, GameDetailResponse::class.java
            )

            setUIAttr(bean.data)
            mBean = bean.data
            mResponseStr = cacheStr

            obtainGameDetail()
        }
    }

    override fun setListener() {
        binding.ivBack.clickWithTrigger {
            finish()
        }

        binding.ivShare.clickWithTrigger {
            if (null != BaseApplication.instance?.getAgentUserInfo()) {//是代理直接分享代理游戏
                ShareDiaFrg()
                    .setShareParam(
                        "${mBean?.gamename}",
                        "${mBean?.subject}",
                        "${mBean?.icon}",
                        "http://h5-share.66wsy.com/ldy?param=$gid-${BaseApplication.instance?.getAgentUserInfo()?.id}"
                    )
                    .show(supportFragmentManager, "分享弹窗")
            } else {
                //判断是否需要登录
                if (null != BaseApplication.instance?.getUserInfo()) {
                    val intent = Intent(this@GameDetailActivity, GameShareActivity::class.java)
                    startActivity(intent)
                } else {
                    startActivity(Intent(this, MobileLoginActivity::class.java))
                }
            }
        }
        binding.ivCollect.clickWithTrigger {
            collectGame()
        }

        binding.srfRefresh.setOnRefreshListener {
            it.finishRefresh(300)

            obtainGameDetail()
        }

        binding.lltGiftBag.clickWithTrigger(200) {
            val intent = Intent(this, GameGiftBagActivity::class.java)
            intent.putExtra("json", mResponseStr)
            startActivity(intent)
        }

        binding.lltActivity.clickWithTrigger(200) {
            val intent = Intent(this, GameActActivity::class.java)
            intent.putExtra("gid", gid)
            startActivity(intent)
        }

        binding.lltCoupon.clickWithTrigger(200) {
            if (null == BaseApplication.instance?.getUserInfo()) {
                startActivity(Intent(this, MobileLoginActivity::class.java))
            } else {
                val intent = Intent(this, GameCouponActivity::class.java)
                intent.putExtra("gid", gid)
                startActivity(intent)
            }
        }

        binding.lltComments.clickWithTrigger(200) {
            val intent = Intent(this, GameCommentActivity::class.java)
            intent.putExtra("gid", gid)
            startActivity(intent)
        }

        binding.tvBtnDownload.clickWithTrigger(800) {
            if (mBean?.isDownload == 0) {
                if (binding.tvBtnDownload.text.toString() == "打开") {
                    try {
                        val intent =
                            packageManager.getLaunchIntentForPackage(mBean?.apkname!!)
                        startActivity(intent)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                } else if (binding.tvBtnDownload.text.toString() == "立即安装") {
                    PackageUtils.installApk(
                        this@GameDetailActivity,
                        "${filePath}/${fileName}"
                    )
                } else if (binding.tvBtnDownload.text.toString()
                        .contains("下载") && binding.tvBtnDownload.text.toString() != "等待下载"
                ) {
                    if (null == BaseApplication.instance?.getUserInfo()) {
                        startActivity(Intent(this, MobileLoginActivity::class.java))
                    } else {
                        obtainDownloadUrl()
                    }
                }
            } else {
                if (binding.tvBtnDownload.text.toString() == "打开") {
                    try {
                        val intent =
                            packageManager.getLaunchIntentForPackage(mBean?.apkname!!)
                        startActivity(intent)
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }
                } else if (binding.tvBtnDownload.text.toString() == "立即安装") {
                    PackageUtils.installApk(
                        this@GameDetailActivity,
                        "${filePath}/${fileName}"
                    )
                } else {
                    ToastUtils.showShort(this@GameDetailActivity, "未开放下载")
                }
            }
        }

        binding.ivDownloadManger.clickWithTrigger {
            startActivity(Intent(this, DownloadManagerActivity::class.java))
        }

        binding.ivDiscount.clickWithTrigger(350) {
            if (mBean?.type == 2) {
                if (null != BaseApplication.instance?.getUserInfo()) {
                    //打开会员礼包详情
                    val intent = Intent(this, VIPGiftBagActivity::class.java)
                    intent.putExtra("gid", gid)
                    startActivity(intent)
                } else {
                    startActivity(
                        Intent(
                            this,
                            MobileLoginActivity::class.java
                        )
                    )
                }
            }
        }
    }

    override fun onDestroy() {
        removeDisposables(this)
        if (isPlay) {
            getCurPlay()?.release()
        }
        //GSYPreViewManager.instance().releaseMediaPlayer();
        //GSYPreViewManager.instance().releaseMediaPlayer();
        orientationUtils?.releaseListener()
        super.onDestroy()
    }

    //下载并安装
    private fun downloadAndInstall() {
//        url =
//            "https://hhdata-1316792546.cos.ap-nanjing.myqcloud.com/data/gift-upgrade-package/hezi_v12.apk"
        if (filePath.isNullOrBlank() or fileName.isNullOrBlank()) {
            return
        }
        Log.e(TAG, "文件路径:${filePath}/${fileName}")
        val downInfo =
            LocalDownloadRecordModel(
                gid,
                mBean!!.icon,
                mBean!!.gamename,
                0f,
                0f,
                0,
                0,
                "$filePath",
                mBean!!.apkname
            )
        DownloadManagerUtils.downloadFile(this@GameDetailActivity, url, downInfo)
    }
}